package com.llcbenwu.controller;

import com.llcbenwu.config.SimpleResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author lilinchun
 * @date 2021/10/25 0025 17:26
 */
@RestController
@Slf4j
public class SecurityController {

    // 获取session中的内容
    private RequestCache requestCache=new HttpSessionRequestCache();

    //用户请求跳转
    private RedirectStrategy redirectStrategy=new DefaultRedirectStrategy();

    private  String url="/llc-signIn.html";

    /**
     * 当需要身份认证时，跳转到这里
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/authentication/require")
    @ResponseStatus(code = HttpStatus.UNAUTHORIZED)  //返回一个401
    public SimpleResponse requireAuthentication(HttpServletRequest request, HttpServletResponse response) throws IOException {
        System.out.println("当需要身份认证时，跳转到这里");
        //当需要认证的接口需要跳转，因为在SecurityConfig中配置 loginPage为登录跳转路径，为了登录之后再跳转到之前需要请求的接口，就需要从session中去拿
        SavedRequest savedRequest = requestCache.getRequest(request, response);
          if(savedRequest !=null){
              //需要跳转请求的url
              String redirectUrl = savedRequest.getRedirectUrl();
              log.info("引发跳转请求的是："+redirectUrl);
              //判断redirectUrl是否是html结尾的
              if (StringUtils.endsWith(redirectUrl,".html")){
                    redirectStrategy.sendRedirect(request,response,url);
              }
          }
        return new SimpleResponse("访问的服务需要身份认证，请引导用户到登录页");
    }
}
